package com.example.selfservicestation.mob

import android.content.Context
import com.example.selfservicestation.util.Logger
import org.greenrobot.eventbus.EventBus

object ScannerManager {

    private val scanners = ArrayList<PortManager>()


    private val advanceScanParser = AdvanceScanParser {
        EventBus.getDefault().post(it)
    }


    fun start(ctx: Context) {
        // 打开第一个扫码头
        Logger.i("SCAN_MGR", "开始打开第一个扫码头")
        PortManager.openScanner1(ctx)
            ?.also {
                Logger.i("SCAN_MGR", "第一个扫码头打开成功，添加进列表")
                scanners.add(it)
            }
        // 打开第二个扫码头
        Logger.i("SCAN_MGR", "开始打开第一个扫码头")
        PortManager.openScanner2(ctx)
            ?.also {
                Logger.i("SCAN_MGR", "第二个扫码头打开成功，添加进列表")
                scanners.add(it)
            }
        Logger.i("SCAN_MGR", "开始监听扫码头事件")
        for ((index, scanner) in scanners.withIndex()) {
            Logger.i("SCAN_MGR", "start listening")
            scanner.listen {
                Logger.d("SCAN_MGR", "刷卡：${it.toHexString()}")
                advanceScanParser.onScanDataRead(ctx, it, scanner,index)
            }
            Logger.i("SCAN_MGR", "complete listening")
        }

        Logger.i("SCAN_MGR", "扫码头监听完成")
    }

    fun startListenScanData(key: Any, listener: (ScanData) -> Unit) {
        advanceScanParser.registerScanDataListener(key, listener)
    }

    fun stopListenScanData(key: Any) {
        advanceScanParser.unregisterScanDataListener(key)
    }

    fun stop() {
        scanners.forEach {
            it.close()
        }
        scanners.clear()
    }

}